package com.firebird.app.reader.pdf.activity

import android.Manifest
import android.annotation.SuppressLint
import android.app.ProgressDialog
import android.content.ContentResolver
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.firebird.app.reader.R
import com.firebird.app.reader.pdf.adapter.ChooseFileAdapter
import com.firebird.app.reader.pdf.adapter.PDFAdapter
import com.firebird.app.reader.pdf.bean.PDFFileInfo
import com.firebird.app.reader.pdf.util.PDFUtil
import com.tbruyelle.rxpermissions2.Permission
import com.tbruyelle.rxpermissions2.RxPermissions
import io.reactivex.functions.Consumer
import java.io.File
import java.util.*

/**
 * @作者: njb
 * @时间: 2019/9/11 20:31
 * @描述: pdf文件查找
 */
class PDFSearchActivity : AppCompatActivity() {
    private var mRecyclerView: RecyclerView? = null
    private var progressDialog: ProgressDialog? = null
    private var pdfAdapter: PDFAdapter? = null
    private var imgBack: ImageView? = null
    private var tvTitle: TextView? = null
    private var tvFinish: TextView? = null
    private val pdfData: ArrayList<PDFFileInfo>? = ArrayList<PDFFileInfo>()
    private val TAG = PDFSearchActivity::class.java.simpleName
    //private String fileName="TBS测试.docx";
//private String fileUrl = "http://pic.oss.xadazhihui.cn/statement/12/2019091116105497151.pdf";
    @SuppressLint("HandlerLeak")
    private val handler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (msg.what == 1) {
                initRecyclerView()
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_pdf_select)
        requestPermission()
        initViews()
        initListener()
    }

    private fun requestPermission() {
        val rxPermissions = RxPermissions(this)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            rxPermissions.requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_SETTINGS)
                    .subscribe(object : Consumer<Permission?>() {
                        fun accept(permission: Permission) {
                            if (permission.granted) { // 用户已经同意该权限
                                Log.d(TAG, permission.name.toString() + " is granted.")
                            } else if (permission.shouldShowRequestPermissionRationale) { // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                                Log.d(TAG, permission.name.toString() + " is denied. More info should be provided.")
                            } else { // 用户拒绝了该权限，并且选中『不再询问』
                                Log.d(TAG, permission.name.toString() + " is denied.")
                            }
                        }
                    })
        }
    }

    private fun searchFile() {
        object : Thread() {
            override fun run() {
                super.run()
                folderData
            }
        }.start()
    }

    private fun initViews() {
        mRecyclerView = findViewById(R.id.rv_pdf)
        imgBack = findViewById(R.id.iv_back)
        tvTitle = findViewById(R.id.tv_title)
        tvFinish = findViewById(R.id.tv_right)
        tvTitle!!.text = "PDF文件搜索"
        imgBack!!.setOnClickListener { finish() }
        showDialog()
        searchFile()
    }

    private fun initListener() {}
    private fun showDialog() {
        progressDialog = ProgressDialog(this, ProgressDialog.THEME_HOLO_LIGHT)
        progressDialog!!.setMessage("正在加载数据中...")
        progressDialog!!.setCanceledOnTouchOutside(false)
        progressDialog!!.show()
    }

    @SuppressLint("NewApi")
    private fun initRecyclerView() {
        pdfAdapter = PDFAdapter(null)
        val notDataView: View = getLayoutInflater().inflate(R.layout.pdf_empty_view, mRecyclerView.getParent() as ViewGroup, false)
        mRecyclerView?.setLayoutManager(LinearLayoutManager(this))
        mRecyclerView?.setAdapter(pdfAdapter)
        pdfAdapter.setOnItemClickListener(object : BaseQuickAdapter.OnItemClickListener() {
            override fun onItemClick(adapter: BaseQuickAdapter, view: View?, position: Int) {
                if (!pdfData!![position].isSelect) {
                    if (selectNumber >= 3) {
                        Toast.makeText(this@PDFSearchActivity, "最多可选择3个文件", Toast.LENGTH_SHORT).show()
                        return
                    }
                }
                for (i in pdfData.indices) {
                    if (i == position) {
                        if (pdfData[i].isSelect) {
                            pdfData[i].setSelect(false)
                        } else {
                            pdfData[i].setSelect(true)
                        }
                    }
                }
                adapter.notifyDataSetChanged()
                tvFinish!!.text = "完成($selectNumber)"
            }
        })
        if (pdfData != null && pdfData.size > 0) {
            for (i in pdfData.indices) {
                pdfData[i].setSelect(false)
            }
            pdfAdapter.setNewData(pdfData)
        } else {
            pdfAdapter.setEmptyView(notDataView)
        }
        progressDialog!!.dismiss()
        //跳转到文件预览
        pdfAdapter!!.setOnItemClickListener(object : BaseQuickAdapter.OnItemClickListener() {
            override fun onItemClick(adapter: BaseQuickAdapter?, view: View?, position: Int) {
                val fileUrl: String = Objects.requireNonNull<Any>(pdfAdapter!!.getItem(position)).getFilePath()
                val fileName: String = Objects.requireNonNull<Any>(pdfAdapter!!.getItem(position)).getFileName()
                PDFPreViewActivity.actionStart(this@PDFSearchActivity, fileUrl, fileName)
            }
        })
    }

    /**
     * 遍历文件夹中资源
     */
    val folderData: Unit
        get() {
            documentData
            handler.sendEmptyMessage(1)
        }

    /**
     * 获取手机文档数据
     *
     * @param
     */
    val documentData: Unit
        get() {
            val columns = arrayOf(MediaStore.Files.FileColumns._ID, MediaStore.Files.FileColumns.MIME_TYPE, MediaStore.Files.FileColumns.SIZE, MediaStore.Files.FileColumns.DATE_MODIFIED, MediaStore.Files.FileColumns.DATA)
            val select = "(_data LIKE '%.pdf')"
            val contentResolver: ContentResolver = getContentResolver()
            val cursor = contentResolver.query(MediaStore.Files.getContentUri("external"), columns, select, null, null)
            var columnIndexOrThrow_DATA = 0
            if (cursor != null) {
                columnIndexOrThrow_DATA = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATA)
            }
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    val path = cursor.getString(columnIndexOrThrow_DATA)
                    val document: PDFFileInfo = PDFUtil.getFileInfoFromFile(File(path))
                    pdfData!!.add(document)
                    Log.d(TAG, " pdf $document")
                }
            }
            cursor!!.close()
        }

    private val selectNumber: Int
        private get() {
            var k = 0
            for (i in pdfData!!.indices) {
                if (pdfData[i].isSelect) {
                    k++
                }
            }
            return k
        }
}